<?php
/**
 * Created by PhpStorm.
 * User: sunjian
 * Date: 2018/3/10
 * Time: 10:28
 */

namespace backend\controllers;

use app\models\ExchangeCate;
use app\models\ExchangeItem;
use yii\helpers\Url;
use yii\web\Controller;
use Yii;
use yii\data\Pagination;
use yii\web\UploadedFile;

class ExchangeItemController extends Controller
{
    public $enableCsrfValidation = false;
    public function actionList(){
        $query = ExchangeItem::find()->orderBy("create_time");
        $countQuery = clone $query;
        $pages = new Pagination(['totalCount' => $countQuery->count(), 'pageSize' => '20']);
        $items = $query->offset($pages->offset)
            ->limit($pages->limit)->asArray()
            ->all();

        $cateList = ExchangeCate::find()->where(['flag'=>1])->asArray()->all();
        $cates =[];
        foreach ($cateList as $v){
            $cates[$v['id']]=$v['title'];
        }
        return $this->render("list",['items'=>$items,'p'=>$pages,'cates'=>$cates]);
    }

    public function actionAdd(){
        $cateList = ExchangeCate::find()->where(['flag'=>1])->asArray()->all();

        return $this->render("add",['cates'=>$cateList]);
    }

    public function actionAddItem(){
        $request = Yii::$app->request;
        if($request->isPost){
            $item = new ExchangeItem();
            $item->title = $request->post("title");
            $item->type = $request->post("type");
            $item->price = $request->post("price");
            $item->cate_id = $request->post("cate_id");
            $item->num = $request->post("num");
            $item->desc = $request->post("editorValue");
            $item->img = $this->uploadImage();
            if($item->save()){
                echo "<script>alert('success!');window.location.href='".Url::to(['exchange-item/list'])."'</script>";
            }else{

                $msg=json_encode($item->errors);
                echo "<script>alert('error!".$msg."');window.history.go(-1)</script>";
            }

        }
    }

    private  function uploadImage()
    {
        $returnPath = '';
        $path = 'uploads';

        $tmp = UploadedFile::getInstanceByName('cover');
        if ($tmp) {
            $patch = $path . '/' . date("YmdHis") ;
            $tmp->saveAs($patch .".".$tmp->getExtension());
            $returnPath .= $patch .".".$tmp->getExtension();
        }

        return $returnPath;
    }
}